import axios from 'axios'
import { getToken, removeToken } from '~/utils/storage/cookie.js'
import { useUserStore } from '~/utils/pinia/user.js'
import { ElMessage } from 'element-plus'
import { eventBus } from '~/utils/common/eventBus.js'
import { getUserToken } from '~/utils/axios/login.js'
import router from '../router/vue-router'
// let router = useRouter()

const URI = '/api'

const mAxios = axios.create({
  baseURL: URI,
  timeout: 10000
})
// const mAjax = axios.create({
//     baseURL: '/cve/api',
//     timeout: 100000
// })
const mAxiosSG = axios.create({
  baseURL: '/api',
  timeout: 100000
})

const requestFn = {
  onFulfilled: function (config) {
    const token = getToken()
    if (token) {
      config.headers['Authorization'] = token
    }
    return config
  },
  onRejected: function (error) {
    console.log(error)
    return Promise.reject(error)
  }
}
// 超时时间重置标识
let isExecuting = false
// 超时时间不包括的url，就是那些请求不触发心跳，比如首页的定时请求,里面参数为正则，因为需要匹配带参数的url；
let notHeartbeatArr = [/^devices\/topology\/(.*?)\/mw\/systemstat\?$/]
const notHeartbeatFn = url => {
  let flag = true
  notHeartbeatArr.forEach(item => {
    if (item.test(url)) {
      flag = false
    }
  })
  return flag
}
const responseFn = {
  onFulfilled: function (response) {
    const res = response
    // 下载文件直接返回
    if (res.type === 'application/octet-stream') {
      return response
    }

    if (res.type === 'application/vnd.ms-excel') {
      return response
    }
    if (res.status === 200) {
      // if (!res.data.succeed && res.data.message) {
      //     ElMessage.error(res.data.message)
      // }
      // 设置每次页面发送数据请求后，重置超时时间，并且每十秒最多只能发送一次心跳；
      // if (!isExecuting && notHeartbeatFn(response.config.url)) {
      //     isExecuting = true;
      //     getUserToken()
      //     // 十秒后重置标志变量
      //     setTimeout(() => {
      //       isExecuting = false;
      //     }, 10000);
      // }
      return response
    } else {
      // ElMessage({
      //     message: res.msg || "Error",
      //     type: "error",
      //     duration: 5 * 1000,
      // });
      // return Promise.reject(new Error(res.msg || "Error"));
    }
  },
  onRejected: function (error) {
    //不应对错误请求做统一处理，应该在业务代码中处理
    console.log(error)
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录过期，请重新登录')
      removeToken()
      sessionStorage.removeItem('user_id')
      sessionStorage.removeItem('username')
      router.push('login')
    } else if (error.response && error.response.status === 502) {
    } else if (error.response && error.response.status === 400) {
      ElMessage({
        message: '等待服务器响应',
        type: 'error',
        duration: 5 * 1000
      })
    } else {
      ElMessage({
        message: '等待服务器响应',
        type: 'error',
        duration: 5 * 1000
      })
    }

    return Promise.reject(error)
  }
}
// 请求前置过滤器
mAxios.interceptors.request.use(requestFn.onFulfilled, requestFn.onRejected)

// 响应数据拦截并做通用处理
mAxios.interceptors.response.use(responseFn.onFulfilled, responseFn.onRejected)

const encodeURL = urlObj => {
  if (typeof urlObj == 'object') {
    Object.keys(urlObj).forEach(function (key) {
      //urlObj[key] = encodeURI(urlObj[key]);
      if (typeof urlObj[key] == 'string') {
        urlObj[key] = urlObj[key].replace(/\s/g, '%20')
      }
    })
  } else {
    urlObj = urlObj.replace(/\s/g, '%20')
  }
  return urlObj
}
const username = sessionStorage.getItem('username')
const log = (res, action) => {
  const params = {
    username,
    result: res.data.succeed ? '成功' : '失败',
    action
  }
  mAxios.post('log', params)
}

export { mAxios, mAxiosSG, encodeURL, URI, log }
